package com.xnyzc.lhy.resource.service.impl.cp;

import com.alibaba.fastjson.JSONObject;
import com.xnyzc.lhy.common.entity.Rv;
import com.xnyzc.lhy.common.exception.PangException;
import com.xnyzc.lhy.common.penum.EErrorCode;
import com.xnyzc.lhy.common.util.CheckUtil;
import com.xnyzc.lhy.common.util.IDUtil;
import com.xnyzc.lhy.resource.entity.cp.OaBankCardAuthenticationRecord;
import com.xnyzc.lhy.resource.mapper.cp.OaBankCardAuthenticationRecordMapper;
import com.xnyzc.lhy.resource.service.cp.BankCardAuditService;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author cuixiaojian
 */
@Slf4j
@Service
public class BankCardAuditServiceImpl implements BankCardAuditService {

    @Autowired
    private OaBankCardAuthenticationRecordMapper oaBankCardAuthenticationRecordMapper;

    /**
     * 银行卡三要素鉴权
     * @param cardNo 银行卡号
     * @param idCard 身份证号
     * @param name 姓名
     * @return Rv
     */
    @Override
    public Rv bankCardAuthentication(String cardNo, String idCard, String name, Long driverId, String tag) {

        String uri = "https://bankcard3c.shumaidata.com/bankcard3c";
        String appCode = "6ca376929b77432da527f72008f07a38";

        StringBuilder url = new StringBuilder("?");
        url.append("idcard").append("=").append(idCard).append("&");
        url.append("name").append("=").append(name).append("&");
        url.append("bankcard").append("=").append(cardNo);

        // 最终地址
        String requestUrl = uri + url.toString();
        log.info("请求最终地址为：{}",requestUrl);

        // 构建http
        OkHttpClient client = new OkHttpClient.Builder().build();
        Request request = new Request.Builder().url(requestUrl).addHeader("Authorization", "APPCODE " + appCode).build();

        Response response = null;
        JSONObject jsonResult = null;
        try {

            response = client.newCall(request).execute();
            String result = response.body().string();

            log.info("请求状态：{}，消息：{}", response.code(), response.message());
            log.info("请求结果返回：{}", result);

            jsonResult = JSONObject.parseObject(result);

        } catch (IOException e) {
            log.error(e.getMessage());
            throw PangException.create(EErrorCode.gatewayDeny);
        }

        Date now = new Date();

        OaBankCardAuthenticationRecord oaBankCardAuthenticationRecord = new OaBankCardAuthenticationRecord();

        // 认证人信息
        oaBankCardAuthenticationRecord.setUserId(driverId);
        oaBankCardAuthenticationRecord.setBankCard(cardNo);
        oaBankCardAuthenticationRecord.setIdCard(idCard);
        oaBankCardAuthenticationRecord.setUserName(name);

        if (CheckUtil.objIsNotEmpty(jsonResult)) {
            // 认证结果信息
            oaBankCardAuthenticationRecord.setResultCode(jsonResult.getInteger("code"));
            oaBankCardAuthenticationRecord.setMessage(jsonResult.getString("msg"));
            if (response.code() == 200) {
                if (200 == jsonResult.getInteger("code")) {
                    JSONObject data = jsonResult.getJSONObject("data");
                    Integer result = data.getInteger("result");
                    oaBankCardAuthenticationRecord.setResult(result);

                    String orderNo = data.getString("order_no");
                    oaBankCardAuthenticationRecord.setOrderNo(orderNo);

                    String desc = data.getString("desc");
                    oaBankCardAuthenticationRecord.setResultDesc(desc);

                    String msg = data.getString("msg");
                    oaBankCardAuthenticationRecord.setResultMsg(msg);
                }
            }
        } else {
            throw PangException.create(EErrorCode.dataParseError);
        }
        oaBankCardAuthenticationRecord.setRecordId(IDUtil.nextId());
        oaBankCardAuthenticationRecord.setTag(tag);
        oaBankCardAuthenticationRecord.setCreateUser(driverId);
        oaBankCardAuthenticationRecord.setCreateTime(now);
        oaBankCardAuthenticationRecord.setUpdateUser(driverId);
        oaBankCardAuthenticationRecord.setUpdateTime(now);

        oaBankCardAuthenticationRecordMapper.insert(oaBankCardAuthenticationRecord);
        return Rv.wrap(oaBankCardAuthenticationRecord);

    }
}
